package com.wuyan.warriorsoffate.ui.view

import android.util.Log
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.material.*
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.*
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.MeasurePolicy
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import com.wuyan.warriorsoffate.ui.theme.WeContentColorFor
import com.wuyan.warriorsoffate.ui.theme.WeTheme
import kotlin.math.max
import kotlin.math.min

//默认带圆角标签
@Composable
fun WeLabel(text:String="", modifier: Modifier=Modifier,
            bgColor: Color= WeTheme.colors.label1,
            contentColor: Color= WeContentColorFor(bgColor),
            shape: Shape=WeTheme.shapes.small,content:@Composable () -> Unit={
        WeText(text = text, modifier = modifier,
            color = contentColor)
    }){
    Row(modifier = modifier
        .background(
            bgColor, shape = shape
        )
        .padding(4.dp)
        .wrapContentSize(),
        verticalAlignment = Alignment.CenterVertically,) {
        content()
    }
}

//自定义的主题适应空间
@Composable
fun WeText(
    text: String,
    modifier: Modifier = Modifier,
    color: Color = WeTheme.colors.text,
    fontSize: TextUnit = WeTheme.typography.body1.fontSize,
    fontStyle: FontStyle? = null,
    fontWeight: FontWeight? = null,
    fontFamily: FontFamily? = null,
    letterSpacing: TextUnit = TextUnit.Unspecified,
    textDecoration: TextDecoration? = null,
    textAlign: TextAlign? = null,
    lineHeight: TextUnit = TextUnit.Unspecified,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    style: TextStyle = LocalTextStyle.current
){
    Text(text,modifier,color,fontSize,fontStyle,fontWeight,fontFamily,letterSpacing,textDecoration,textAlign,lineHeight,overflow,softWrap,maxLines,onTextLayout,style)
}
@Composable
fun WeText(text: AnnotatedString,
           modifier: Modifier = Modifier,
           color: Color = WeTheme.colors.text,
           fontSize: TextUnit = WeTheme.typography.body1.fontSize,
           fontStyle: FontStyle? = null,
           fontWeight: FontWeight? = null,
           fontFamily: FontFamily? = null,
           letterSpacing: TextUnit = TextUnit.Unspecified,
           textDecoration: TextDecoration? = null,
           textAlign: TextAlign? = null,
           lineHeight: TextUnit = TextUnit.Unspecified,
           overflow: TextOverflow = TextOverflow.Clip,
           softWrap: Boolean = true,
           maxLines: Int = Int.MAX_VALUE,
           inlineContent: Map<String, InlineTextContent> = mapOf(),
           onTextLayout: (TextLayoutResult) -> Unit = {},
           style: TextStyle = LocalTextStyle.current){
    Text(text,modifier,color,fontSize,fontStyle,fontWeight,fontFamily,letterSpacing,
        textDecoration,textAlign,lineHeight,overflow,softWrap,maxLines,inlineContent,onTextLayout,style)
}


@Composable
fun WeButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    elevation: ButtonElevation? = ButtonDefaults.elevation(),
    shape: Shape = MaterialTheme.shapes.small,
    border: BorderStroke? = null,
    colors: ButtonColors = ButtonDefaults.buttonColors(
        backgroundColor = WeTheme.colors.text,
        contentColor =  WeTheme.colors.onText,
        disabledBackgroundColor = WeTheme.colors.bg.copy(alpha = 0.12f)
            .compositeOver(WeTheme.colors.onBg),
        disabledContentColor = WeTheme.colors.text
            .copy(alpha = ContentAlpha.disabled)
        ),
    contentPadding: PaddingValues = PaddingValues(all = WeTheme.weDp.paddingSmall/2),
    text: String="",
    content: @Composable RowScope.() -> Unit = {
        WeText(text = text,
            color = colors.contentColor(enabled).value)
    }
) {
    val contentColor by colors.contentColor(enabled)
    Surface(
        modifier = modifier.clickable(interactionSource = interactionSource,
            indication = rememberRipple(),
            enabled = enabled,
            role = Role.Button,
            onClick = onClick),
        shape = shape,
        color = colors.backgroundColor(enabled).value,
        contentColor = contentColor,
        border = border,
        elevation =elevation?.elevation(enabled, interactionSource)?.value ?: 0.dp,){
        CompositionLocalProvider(LocalContentAlpha provides contentColor.alpha) {
            ProvideTextStyle(
                value = MaterialTheme.typography.button
            ) {
                Row(
                    Modifier
                        .defaultMinSize(
                            minWidth = WeTheme.weDp.paddingLarge * 2,
                            minHeight = WeTheme.weDp.paddingLarge
                        )
                        .padding(contentPadding),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically,
                    content = content
                )
            }
        }
    }
}
@Composable
fun WeSurface(
    modifier: Modifier = Modifier,
    shape: Shape = RectangleShape,
    color: Color = WeTheme.colors.bg,
    contentColor: Color = WeContentColorFor(color),
    border: BorderStroke? = null,
    elevation: Dp = 0.dp,
    content: @Composable () -> Unit
){
    Surface(modifier,shape,color,contentColor,border,elevation,content)
    //StaggeredGridLayoutManager
}
//自定义自动适应布局
@Composable
fun StaggeredGrid(modifier: Modifier= Modifier,
    //每行的元素对其方式
                  itemAlign:StaggeredGridItemAlign=StaggeredGridItemAlign.Center,
                  padding:Dp=3.dp,
                  content:@Composable () -> Unit){
    val measurePolicy = MeasurePolicy { measurables, constraints ->


        val placeables = measurables.mapIndexed { index, child ->
            val placeable = child.measure(
                Constraints(
                    0,
                    constraints.maxWidth,
                    0,
                    constraints.maxHeight
                )
            )
            // 每次测量后更新 children 占据的空间
            placeable
        }
        //子元素索引
        var index=0
        //最小宽度
        var minWidth=Int.MAX_VALUE
        //最小高度
        var minHeight=0
        //所有行子元素个数
        val itemsNum= mutableListOf<Int>()
        //每行高度偏移
        val rowsWidth=mutableListOf<Int>()
        val rowsHeight=mutableListOf<Int>()
        while (index<placeables.size){
            //当前行最小宽度
            var rowMinWidth=0
            //每行子元素个数
            var count=0
            //每行最大高度
            var rowMaxHeight=0

            while (index<placeables.size&&constraints.maxWidth-rowMinWidth>0){
                if (constraints.maxWidth-rowMinWidth-placeables[index].width>0){
                    rowMinWidth+=placeables[index].width+padding.toPx().toInt()
                }else if (count==0){
                    rowMinWidth=constraints.maxWidth
                }else{
                    break
                }
                rowMaxHeight= max(rowMaxHeight,placeables[index].height)
                ++count
                ++index
            }
            rowsWidth.add(rowMinWidth-padding.toPx().toInt())
            rowsHeight.add(rowMaxHeight)
            minHeight+=rowMaxHeight+padding.toPx().toInt()
            itemsNum.add(count)
        }
        if (constraints.hasFixedWidth){
            minWidth=constraints.maxWidth
        }else{
            minWidth=rowsWidth.maxOf {
                it
            }
        }
        if (constraints.hasFixedHeight){
            minHeight=constraints.maxHeight
        }else{
            minHeight-=padding.toPx().toInt()
        }
        layout(minWidth,minHeight) {
            if (placeables.isEmpty()){
                return@layout
            }
            //当前行
            var i=0
            var j=0
            var x=0
            var y=0
            if (itemAlign==StaggeredGridItemAlign.End){
                x=minWidth-rowsWidth[i]
            }else if (itemAlign==StaggeredGridItemAlign.Center&&itemsNum[i]==1){
                x=((minWidth-rowsWidth[i]).toFloat()/2f).toInt()
            }
            placeables.forEachIndexed { index,placeable ->
                // 放置每一个 child
                placeable.placeRelative(x,y+(rowsHeight[i]-placeable.height)/2)
                if (j==itemsNum[i]-1){
                    y+=rowsHeight[i]+padding.toPx().toInt()
                    j=0
                    ++i
                    if (itemAlign==StaggeredGridItemAlign.End){
                        x=minWidth-rowsWidth[i]
                    }else if (itemAlign==StaggeredGridItemAlign.Center&&i<itemsNum.size&&itemsNum[i]==1){
                        x=((minWidth-rowsWidth[i]).toFloat()/2f).toInt()
                    }else{
                        x=0
                    }
                }else{
                    ++j
                    x+=(padding.toPx()).toInt()+placeable.width
                    if (itemAlign==StaggeredGridItemAlign.Center){
                        x+=((minWidth-rowsWidth[i]).toFloat()/itemsNum[i]).toInt()
                    }
                }
            }
        }
    }
    Layout(content = content, modifier = modifier
        .padding(padding), measurePolicy = measurePolicy)
}
enum class StaggeredGridItemAlign{
    Start,
    Center,
    End,
}
@Composable
fun InfiniteTransitionSizeAnimate(initialValue:Float = 1f,
                                  targetValue:Float = 0.7f,
                                  durationMillis:Int=1000,
                                  modifier:Modifier = Modifier,
                                  content:@Composable () -> Unit){
    val infiniteTransition = rememberInfiniteTransition()
    val zoom by infiniteTransition.animateFloat(
        initialValue = initialValue,
        targetValue = targetValue,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis, easing = LinearEasing),
            repeatMode = RepeatMode.Reverse
        )
    )
    Box(modifier = modifier
        .wrapContentSize()
        .scale(zoom)) {
        content()
    }
}